document.addEventListener('DOMContentLoaded', function () {
    const inputs = document.querySelectorAll('.input-field');
    inputs.forEach((input, index) => {
        input.addEventListener('input', function () {
            if (this.value.length === this.maxLength) {
                const nextInput = inputs[index + 1];
                if (nextInput) {
                    nextInput.focus();
                }
            }
        });

        // 允许删除字符时也能回退到上一个输入框
        input.addEventListener('keydown', function (event) {
            if (event.key === 'Backspace' && this.value === '') {
                const previousInput = inputs[index - 1];
                if (previousInput) {
                    previousInput.focus();
                }
            }
        });

        // 剪切板联动
        input.addEventListener('paste', function (event) {
            event.preventDefault(); // 阻止默认粘贴行为

            const pastedData = (event.clipboardData || window.clipboardData).getData('text');
            const digits = pastedData.trim().split('');

            // 清空所有输入框
            inputs.forEach(input => input.value = '');

            // 将数字分配给输入框
            digits.slice(0, 4).forEach((digit, i) => {
                inputs[i].value = digit;
            });
        });
    });
});
document.getElementById('joinGameRoomButton').addEventListener('click', function () {
    ZhhSessionStorage_clear();
    let roomCode = "";
    for (let i = 1; i <= 4; i++) {
        let input = document.getElementById("roomCode" + i);
        roomCode += input.value;
    }
    if (roomCode.length !== 4) {
        popUpMessageShow("请输入4位房间号");
        return;
    }
    getRoomDetail(roomCode).then(response => {
        ZhhSessionStorage_setItem('roomCode', roomCode);
        window.location.href = "/zhh/view/chessboard";
    }).catch(error => {
        popUpMessageShow(error.message);
    })

});

document.getElementById('createGameRoomButton').addEventListener('click', function () {
    ZhhSessionStorage_clear();
    createRoom().then(response => {
        ZhhSessionStorage_setItem('roomCode', response);
        window.location.href = "/zhh/view/chessboard";
    });
});